using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;
using System.Net;
using System.IO;

public partial class forums_controls_usercp_EditAvatar : Controls.DataManagerUserControl
{
    protected override void ItemChanged()
    {
        if (CurrentUser != null)
        {
            mviewAvatar.SetActiveView(viewAvatar);
            RefreshAvatar();
            Page.Title = "FSTDT Forums: " + "Edit Avatar";
        }
        else
        {
            mviewAvatar.SetActiveView(viewError);
            Page.Title = "FSTDT Forums: " + "Oops!";
        }
    }
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        CurrentUser.AvatarExtension = null;
        DAL.Users.Save(CurrentUser);
        RefreshAvatar();
    }

    private void RefreshAvatar()
    {
        // random number appended to the URL prevents the browser from display cached version 
        // of the avatar.
        imgAvatar.ImageUrl = Helpers.StringHelper.SafeFormat("~/forums/avatars/{0}.{1}?{2}",
                CurrentUser.ID,
                CurrentUser.AvatarExtension,
                new Random().NextDouble());

        if (String.IsNullOrEmpty(CurrentUser.AvatarExtension))
        {
            mviewCurrentAvatar.SetActiveView(viewNoAvatar);
        }
        else
        {
            mviewCurrentAvatar.SetActiveView(viewCurrentAvatar);
        }
    }
    
    protected void UploadFromFile()
    {
        if (uploadAvatar.HasFile)
        {
            TryUploadFile(uploadAvatar.PostedFile.ContentType, uploadAvatar.PostedFile.InputStream);
            uploadAvatar.PostedFile.InputStream.Close();
        }
    }

    private bool IsImage(string contentType, out System.Drawing.Imaging.ImageFormat format)
    {
        bool success = false;
        format = null;
        foreach (Match m in Regex.Matches(contentType, "(?<ext>gif|jpe?g|bmp|png)"))
        {
            success = true;
            switch (m.Groups["ext"].Value.ToLower())
            {
                case "gif":
                    format = System.Drawing.Imaging.ImageFormat.Gif;
                    break;
                case "jpg":
                case "jpeg":
                    format = System.Drawing.Imaging.ImageFormat.Jpeg;
                    break;
                case "png":
                    format = System.Drawing.Imaging.ImageFormat.Png;
                    break;
                default:
                    format = System.Drawing.Imaging.ImageFormat.Bmp;
                    break;
            }
            break;
        }

        return success;
    }

    private void PrintMsg(string msg, bool isError)
    {
        if (isError)
        {
            lblMsg.ForeColor = System.Drawing.Color.Red;
        }
        else
        {
            lblMsg.ForeColor = System.Drawing.Color.Green;
        }
        lblMsg.Text = msg;
    }

    private void PrintMsg(string msg)
    {
        PrintMsg(msg, true);
    }


    private bool TrySaveImage(System.IO.Stream imageStream, System.Drawing.Imaging.ImageFormat outputFormat)
    {
        bool success = false;

        // image must be less than 25 kb
        if ((imageStream.Length <= 25600) || (CurrentItem.HasPermissions(DAL.User.UserStatus.Moderator)))
        {
            System.Drawing.Bitmap b = new System.Drawing.Bitmap(imageStream);

            if (b.Size.IsEmpty)
            {
                PrintMsg("Does not compute. Not a valid image file.");
            }
            else
            {
                // image must be 100 x 100 or less
                if ((b.Height <= 100 && b.Width <= 100) || (CurrentUser.HasPermissions(DAL.User.UserStatus.Moderator)))
                {
                    string fileExt = outputFormat.ToString().ToLower().Replace("jpeg", "jpg");
                    string fileName = string.Format("{0}.{1}", CurrentUser.ID, fileExt);

                    try
                    {
                        PrintMsg("Avatar uploaded successfully.", false);

                        /*

                        b.Save(Server.MapPath("~/forums/avatars/" + fileName), outputFormat);
                        CurrentUser.AvatarExtension = fileExt;
                        DAL.Users.Save(CurrentUser);
                        */

                        FtpWebRequest ftp = (FtpWebRequest)WebRequest.Create(@"ftp://70.85.251.170/fstdt.com/fstdt.com/forums/avatars/testupload.img");
                        string u = ConfigurationManager.AppSettings["fu"];
                        string p = ConfigurationManager.AppSettings["fp"];
                        ftp.Credentials = new NetworkCredential(u, p);
                        ftp.Method = WebRequestMethods.Ftp.UploadFile;

                        using (Stream s = ftp.GetRequestStream())
                        {
                            byte[] data = new byte[imageStream.Length];
                            s.Read(data, 0, (int)imageStream.Length);
                            s.Write(data, 0, data.Length);
                        }
                        

                        
                        success = true;
                    }
                    catch (Exception ex)
                    {
                        PrintMsg(string.Format("An error occurred: {0}", ex.Message));
                    }
                }
                else
                {
                    PrintMsg("Does not compute. Your avatar can't be larger than 100 x 100 pixels.");
                }
            }
        }
        else
        {
            PrintMsg("Does not compute. Your avatar can't be larger than 25 kb.");
        }

        return success;
    }

    protected void UploadFromUrl()
    {
        if (Uri.IsWellFormedUriString(txtUrl.Text, UriKind.Absolute))
        {
            System.Net.WebClient web = new System.Net.WebClient();
            System.IO.MemoryStream mystream = new System.IO.MemoryStream(web.DownloadData(txtUrl.Text));
            TryUploadFile(web.ResponseHeaders[System.Net.HttpResponseHeader.ContentType], mystream);
            mystream.Close();
        }
        else
        {
            PrintMsg("Not a valid URL.");
        }
    }

    protected void TryUploadFile(string contentType, System.IO.Stream filestream)
    {
        System.Drawing.Imaging.ImageFormat format;
        if (IsImage(contentType, out format))
        {
            if (TrySaveImage(filestream, format))
            {
                RefreshAvatar();
            }
        }
        else
        {
            PrintMsg("Not a valid image file.");
        }
    }
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (uploadAvatar.HasFile)
        {
            UploadFromFile();
        }
        else
        {
            UploadFromUrl();
        }
        txtUrl.Text = "";
    }
}
